package com.woniuxy.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.crm.entity.Product;
import com.woniuxy.crm.result.Result;
import com.woniuxy.crm.service.IProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 产品表 前端控制器
 *
 * @author 郑鹏
 * @since 2024-08-12
 */
@RestController
@RequestMapping("/admin/product")
@Tag(name = "产品表接口")
public class ProductController {

    @Autowired
    private IProductService productService;

    // 新增或者更新
    @PostMapping("/saveOrUpdate")
    @Operation(summary = "新增或者修改")
    public Result save(@RequestBody Product product) {
        productService.saveOrUpdate(product);
        return Result.ok();
    }

    @DeleteMapping("/deleteById")
    @Operation(summary = "根据id删除")
    public Result delete(@RequestParam Long id) {
        productService.removeById(id);
        return Result.ok();

    }

    @GetMapping("list")
    @Operation(summary = "查询全部")
    public Result<List<Product>> findAll() {
        List<Product> products = productService.list();
        return Result.ok(products);

    }

    @GetMapping("/getById")
    @Operation(summary = "根据id查询")
    public Result<Product> findOne(@RequestParam Long id) {
        Product product = productService.getById(id);
        return Result.ok(product);
    }

    @GetMapping("listByCatagoryId")
    @Operation(summary = "根据类型id查询")
    public Result<List<Product>> findByCatagoryId(@RequestParam Long categoryId) {
        LambdaQueryWrapper <Product> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(Product::getCategoryId,categoryId);
        List<Product> products = productService.list(lambdaQuery);
        return Result.ok(products);
    }
    @GetMapping("/page")
    @Operation(summary = "分页查询")
    public Result<Page<Product>> findPage(@RequestParam Integer pageNum,
                                          @RequestParam Integer pageSize,
                                          @RequestParam(required = false) Long categoryId) {
        LambdaQueryWrapper<Product> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.orderByDesc(Product::getId);
        lambdaQuery.eq(categoryId!=null,Product::getCategoryId,categoryId);
        Page<Product> Page = productService.page(new Page<>(pageNum, pageSize), lambdaQuery);
        return Result.ok(Page);
    }

}

